package win.zxshuo.www.spider;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import win.zxshuo.www.service.BookService;
import win.zxshuo.www.utils.StringUtils;

@Component
public class QidianSpider extends BaseSpider {
    Log logger = LogFactory.getLog(getClass());

    @Autowired
    BookService bookService;


    /**
      * @Description: 直接通过起点书籍页面获取书籍信息
      * @Author: RffanLAB
      * @Params: 书籍页面url
      * @Returns:
      * @CreateDate: 2018/3/21
      */
    public void getBookinfo(String url) throws Exception{
        try {
            Document document = getPageContent(url);
            Element bookinfo = document.selectFirst(".book-information.cf");
            Element detailInfo = bookinfo.selectFirst(".book-info");
            String surface = bookinfo.selectFirst(".book-img").selectFirst("img").attr("src").replace("\r","");
            String author = detailInfo.selectFirst("h1").selectFirst("a").ownText().replace("\r","");
            Element tags = bookinfo.selectFirst("p.tag");
            String category = tags.selectFirst("a.red").ownText().replace("\r","");
            String bookStatus = tags.selectFirst("span.blue").ownText().replace("\r","");
            Integer status = 0;
            if (bookStatus.equals("完本")){
                status = 1;
            }
            String bookName = detailInfo.selectFirst("em").ownText().replace("\r","");
            String markString = bookinfo.selectFirst("#commentWrap").selectFirst("h4").text().replace("\r","");
            Double mark = new Double(markString);
            // 开始获取简介了
            Element bookContent = document.selectFirst(".book-content-wrap.cf");
            String bookIntro = bookContent.selectFirst(".book-intro p").html();
            bookService.addNewBook(bookName,surface,category,author,StringUtils.changeBrToP(bookIntro),status,mark,url);


        }catch (Exception e){
            logger.info("通过Url获取书籍信息失败");
            logger.error(e.getMessage());
            throw new Exception(e.getMessage());
        }
    }

    /**
      * @Description:采集起点的排行的25页数据信息
      * @Author: RffanLAB
      * @Params: url 该url为基础的url没有添加分页的。例如地址为：https://www.qidian.com/rank/yuepiao?style=1&page=1 传入的伪https://www.qidian.com/rank/yuepiao?style=1&page=
      * @Returns:
      * @CreateDate: 2018/3/21
      */
    public void getRankingBookinfo(String url) throws Exception {
        try {
            for (int i = 1 ;i<=25;i++){
                String totalUrl = url+i;
                getOnePageRank(totalUrl);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            throw new Exception(e.getMessage());
        }
    }

    public void getOnePageRank(String url) throws Exception{
        try {
            Document document = getPageContent(url);
            Element rankViewList = document.selectFirst("#rank-view-list");
            if (rankViewList != null){
                Elements elements = rankViewList.select("li");
                System.out.println(elements.size());
                for (Element element:elements){
                    // 书名
                    Element bookMidInfo = element.selectFirst(".book-mid-info");
                    String bookname = bookMidInfo.selectFirst("a").ownText();
                    // 封面
                    Element bookImgBox = element.selectFirst(".book-img-box");
                    String surface = "https:"+bookImgBox.selectFirst("a").selectFirst("img").attr("src");
                    // 分类
                    Element authorEle = bookMidInfo.selectFirst("p.author");
                    String authorEleText = authorEle.text();
                    String[] strs = authorEleText.split("[|]");
                    String category = strs[1].trim();
                    // 作者
                    String author = strs[0].trim();
                    // 简介
                    String intro = bookMidInfo.selectFirst("p.intro").text();
                    // 状态
                    String statusStr = strs[2].trim();
                    Integer status = 0;
                    if (statusStr.equals("完本")){
                        status = 1;
                    }
                    // 评分 mark
                    Double mark = 0.0;
                    // 起点链接
                    String qidianUrl = "https:"+ bookMidInfo.selectFirst("h4").selectFirst("a").attr("href");
                    bookService.addNewBook(bookname,surface,category,author,StringUtils.changeBrToP(intro),status,mark,qidianUrl);
                }
            }
        }catch (Exception e){
            logger.info("获取单个页面排行的出错了");
            logger.info(e.getCause());
            logger.error(e.getLocalizedMessage());
            logger.error(e.getStackTrace());
            logger.info("URL是："+url);
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }

}
